package org.red_cross_service.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.red_cross_service.common.anno.NoNeedToken;
import org.red_cross_service.common.response.Response;
import org.red_cross_service.domain.entity.UserEntity;
import org.red_cross_service.service.UserService;
import org.red_cross_service.utils.HttpUtils;


@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {

    @Autowired
    ControllerComponent controllerComponent;

    @Autowired
    private UserService userService;

    @NoNeedToken
    @PostMapping("/login")
    public Response login(@RequestParam String code,@RequestBody UserEntity user) {
        if( code == null){
            return Response.error("参数为空！");
        }
        String url = controllerComponent.getLogin().createUrl(code);
        JSONObject res = HttpUtils.sendGet(url);
//        UserEntity userEntity = new UserEntity();
        user.setOpenId(res.getString("openid"));
        if (user.getOpenId() != null) return controllerComponent.getUserService().login(user);
        return Response.error("网络异常, 请稍后重试");
    }
    @NoNeedToken
    @GetMapping("/autoLogin")
    public Response autoLogin(@RequestParam String code){
        if(code == null) return Response.error("参数为空！");
        String url = controllerComponent.getLogin().createUrl(code);
        JSONObject res = HttpUtils.sendGet(url);
        String openId = res.getString("openid");
        if(openId == null) return Response.success("为查询到用户",null);
        return userService.autoLogin(openId);
    }



    @NoNeedToken
    @RequestMapping("/getUserAvatar")
    public Response getUserAvatar(@RequestParam String idCard){
        if(idCard == null){
            return Response.error("身份证号不能为空");
        }
        return userService.getUserAvatar(idCard);
    }

    @NoNeedToken
    @GetMapping("/getOne")
    public Response getUserOne(@RequestParam Integer userId){
        return userService.getUserOne(userId);
    }

    @NoNeedToken
    @PostMapping("/list")
    public Response getUserList(@RequestBody UserEntity user){
        return userService.getUserList(user);
    }

    //更新
    @NoNeedToken
    @PostMapping("/update")
    public Response updateUser(@RequestBody UserEntity user){
        return userService.updateUser(user);
    }
    @NoNeedToken
    @PostMapping("/export")
    public void exportUser(HttpServletResponse response, @RequestBody UserEntity user){
        userService.exportUser(response,user);
    }


}
